﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;

namespace DTcms.Common
{
    public class VideoHelper
    {
        #region 配置
        private string ffmpegtool = Utils.GetXmlMapPath("ffmpeg");//ffmpeg绝对路径
        private string ffplaytool = Utils.GetXmlMapPath("ffplay");//ffplay绝对路径
        private string ffprobetool = Utils.GetXmlMapPath("ffprobe");//ffprobe绝对路径
        #endregion

        #region 视频格式转为Flv
        /// <summary>
        /// Converts the flv.
        /// </summary>
        /// <returns><c>true</c>, if flv was converted, <c>false</c> otherwise.</returns>
        /// <param name="vFileName">原视频文件地址</param>
        /// <param name="ExportName">生成后的Flv文件地址</param>
        public bool ConvertFlv(string vFileName, string ExportName)
        {
            if ((!File.Exists(ffmpegtool)) || (!File.Exists(Utils.GetMapPath(vFileName))))
            {
                return false;
            }

            vFileName = Utils.GetMapPath(vFileName);
            ExportName = Utils.GetMapPath(ExportName);
            string Command = " -i \"" + vFileName + "\" -y -ab 32 -ar 22050 -b 800000 -s  480*360 \"" + ExportName + "\""; //Flv格式     
            Process p = new Process();
            p.StartInfo.FileName = ffmpegtool;
            p.StartInfo.Arguments = Command;
            p.StartInfo.WorkingDirectory = Utils.GetMapPath("~/tools/");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = false;
            p.Start();
            p.BeginErrorReadLine();
            p.WaitForExit();
            p.Close();
            p.Dispose();
            return true;
        }
        #endregion

        #region 生成Flv视频的缩略图       
        /// <summary>
        /// 生成Flv视频的缩略图
        /// </summary>
        /// <param name="vFileName">视频文件地址</param>
        /// <param name="sizeOfImg">140x110</param>
        /// <returns>返回视频缩略图位置</returns>
        public string CatchImg(string vFileName, string sizeOfImg)
        {
            if ((!File.Exists(ffmpegtool)) || (!File.Exists(Utils.GetMapPath(vFileName)))) return "";
            try
            {
                string flv_img_p = vFileName.Substring(0, vFileName.Length - 4) + ".jpg";
                string Command = " -i " + Utils.GetMapPath(vFileName) + " -y -f image2 -t 0.1 -s " + sizeOfImg + " " + Utils.GetMapPath(flv_img_p);
                Process p = new Process();
                p.StartInfo.FileName = ffmpegtool;
                p.StartInfo.Arguments = Command;
                p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                try
                {
                    p.Start();
                }
                catch
                {
                    return "";
                }
                finally
                {
                    p.Close();
                    p.Dispose();
                }
                System.Threading.Thread.Sleep(4000);

                //注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
                if (Utils.FileExists(flv_img_p))
                {
                    return flv_img_p;
                }
                return "";
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 运行FFMpeg的视频解码(绝对路径)
        /// <summary>
        /// 转换文件并保存在指定文件夹下
        /// </summary>
        /// <param name="fileName">上传视频文件的路径（原文件）</param>
        /// <param name="playFile">转换后的文件的路径（网络播放文件）</param>
        /// <param name="imgFile">从视频文件中抓取的图片路径</param>
        /// <param name="FlvImgSize">图片的尺寸如:240*180</param>
        /// <returns>成功:返回图片虚拟地址;失败:返回空字符串</returns>
        public string ChangeFilePhy(string fileName, string playFile, string imgFile, int widthOfFile, int heightOfFile, string FlvImgSize)
        {
            string ffmpeg = Utils.GetMapPath(ffmpegtool);
            if ((!File.Exists(ffmpeg)) || (!File.Exists(fileName)))
            {
                return "";
            }
            string flv_file = Path.ChangeExtension(playFile, ".flv");
            ProcessStartInfo FilestartInfo = new ProcessStartInfo(ffmpeg)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                Arguments = " -i " + fileName + " -ab 56 -ar 22050 -b 500 -r 15 -s " + widthOfFile + "x" + heightOfFile + " " + flv_file
            };
            try
            {
                Process.Start(FilestartInfo);//转换
                CatchImg(fileName, imgFile); //截图
            }
            catch
            {
                return "";
            }
            return "";
        }

        /// <summary>
        /// 视频截图
        /// </summary>
        /// <param name="fileName">视频路径</param>
        /// <param name="imgFile">图片保存路径</param>
        /// <param name="FlvImgSize">图片的尺寸如:240*180</param>
        /// <param name="CutTimeFrame">设置开始获取帧的视频时间</param>
        /// <returns></returns>
        public string CatchImg(string fileName, string imgFile, string FlvImgSize, string CutTimeFrame = "2")
        {
            fileName = Utils.GetMapPath(fileName);
            string flv_img = Utils.GetMapPath(imgFile);
            ProcessStartInfo ImgstartInfo = new ProcessStartInfo(ffmpegtool)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                Arguments = "   -i   " + fileName + "  -y  -f  image2   -ss " + CutTimeFrame + " -vframes 1  -s   " + FlvImgSize + "   " + flv_img
            };
            try
            {
                Process.Start(ImgstartInfo);
            }
            catch
            {
                return "";
            }
            System.Threading.Thread.Sleep(4000);
            if (Utils.FileExists(imgFile))
            {
                return imgFile;
            }
            return "";
        }
        #endregion

        #region 运行FFMpeg的视频解码(相对路径)
        /// <summary>
        /// 转换文件并保存在指定文件夹下
        /// </summary>
        /// <param name="fileName">上传视频文件的路径（原文件）</param>
        /// <param name="playFile">转换后的文件的路径（网络播放文件）</param>
        /// <param name="imgFile">从视频文件中抓取的图片路径</param>
        /// <param name="sizeOfImg">140x110</param>
        /// <returns>成功:返回图片虚拟地址;失败:返回空字符串</returns>
        public string ChangeFileVir(string fileName, string playFile, string imgFile, int widthOfFile, int heightOfFile, string FlvImgSize)
        {
            string ffmpeg = Utils.GetMapPath(ffmpegtool);
            if ((!File.Exists(ffmpeg)) || (!File.Exists(fileName)))
            {
                return "";
            }
            string flv_img = Path.ChangeExtension(Utils.GetMapPath(imgFile), ".jpg");
            string flv_file = Path.ChangeExtension(Utils.GetMapPath(playFile), ".flv");

            ProcessStartInfo ImgstartInfo = new ProcessStartInfo(ffmpeg)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                Arguments = "   -i   " + fileName + "   -y   -f   image2   -t   0.001   -s   " + FlvImgSize + "   " + flv_img
            };
            ProcessStartInfo FilestartInfo = new ProcessStartInfo(ffmpeg)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                Arguments = " -i " + fileName + " -ab 56 -ar 22050 -b 500 -r 15 -s " + widthOfFile + "x" + heightOfFile + " " + flv_file
            };
            try
            {
                Process.Start(FilestartInfo);
                Process.Start(ImgstartInfo);
            }
            catch
            {
                return "";
            }

            ///注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;   
            ///这儿需要延时后再检测,我服务器延时8秒,即如果超过8秒图片仍不存在,认为截图失败;    
            if (File.Exists(flv_img))
            {
                return flv_img;
            }
            return "";
        }
        #endregion

        #region 运行mencoder的视频解码器转换(绝对路径)
        /// <summary>
        /// 运行mencoder的视频解码器转换
        /// <param name="FlvImgSize">140x110</param>
        /// </summary>
        public string MChangeFilePhy(string vFileName, string playFile, string imgFile, int widthOfFile, int heightOfFile, string FlvImgSize)
        {
            string tool = Utils.GetMapPath(ffprobetool);
            if ((!File.Exists(tool)) || (!File.Exists(vFileName)))
            {
                return "";
            }
            string flv_file = Path.ChangeExtension(playFile, ".flv");
            ProcessStartInfo FilestartInfo = new ProcessStartInfo(tool)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                Arguments = " " + vFileName + " -o " + flv_file
                    + " -of lavf -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=200:mbd=2:mv0:trell:v4mv:cbp:last_pred=1:dia=-1:cmp=0:vb_strategy=1 -vf scale="
                    + widthOfFile + ":" + heightOfFile + " -ofps 12 -srate 22050"
            };
            try
            {
                Process.Start(FilestartInfo);
                CatchImg(flv_file, imgFile);
            }
            catch
            {
                return "";
            }
            return "";
        }
        #endregion
    }
}
